package com.mxf.code.redisson_demo.task;

import com.mxf.code.redisson_demo.DistributedLocker;
import com.mxf.code.util.RedisUtils1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : TaskDemo
 * @description : [描述说明该类的功能]
 * @createTime : [2022/10/9 18:25]
 * @updateUser : [mxf]
 * @updateTime : [2022/10/9 18:25]
 * @updateRemark : [描述说明本次修改内容]
 */
@RestController
@Slf4j
public class TaskDemo {
    @Autowired
    private RedisUtils1 redisUtils1;

    @Autowired
    private DistributedLocker distributedLocker;


    public static final String REDISSION_KEY = "test";

    @GetMapping("/test")
    public void init() {
        boolean redission = redisUtils1.set("redission", 1);
        log.info("redission新增：{}", redission);
    }

    //@Scheduled(cron = "*/10 * * * * ?")
    public void doRun() throws InterruptedException {
        try {
            boolean b = distributedLocker.tryLock(REDISSION_KEY, TimeUnit.SECONDS, -1);
            while (!b) {
                Thread.sleep(1000L);
                b = distributedLocker.tryLock(REDISSION_KEY, TimeUnit.SECONDS, -1);
            }

            Thread.sleep(15000L);
            long count = redisUtils1.incr("redission", 1);
            log.info("concurent:{},count:{}", new Date(), count);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            distributedLocker.unlock(REDISSION_KEY);
            Thread.sleep(1000L);
        }
    }
}
